package com.hanshg.cherry.security.xss;

import com.hanshg.cherry.util.core.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * @ClassName XssHttpServletRequestWrapper
 * @Description XSS请求适配器
 * @Author 柠檬水
 * @Date 2020/4/12 10:15
 * @Version 1.0
 **/
@Slf4j
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        String strHeader = super.getHeader(name);
        if (StringUtils.isEmpty(strHeader)) {
            return strHeader;

        }
        return Jsoup.clean(super.getHeader(name), Whitelist.relaxed());
    }

    @Override
    public String getParameter(String name) {
        String strParameter = super.getParameter(name);
        if (StringUtils.isEmpty(strParameter)) {
            return strParameter;
        }
        return Jsoup.clean(super.getParameter(name), Whitelist.relaxed());
    }


    @Override
    public String[] getParameterValues(String name) {
        String[] values = super.getParameterValues(name);
        if (values == null) {
            return values;
        }
        int length = values.length;
        String[] escapseValues = new String[length];
        for (int i = 0; i < length; i++) {
            //过滤一切可能的xss攻击字符串
            escapseValues[i] = Jsoup.clean(values[i], Whitelist.relaxed()).trim();
            if (!StringUtils.equals(escapseValues[i], values[i])) {
                log.debug("xss字符串过滤前：" + values[i] + "\r\n" + "过滤后：" + escapseValues[i]);
            }
        }
        return escapseValues;
    }
}
